#include <iostream>

#include <pthread.h>
#include <unistd.h>

int cnt = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;  // 全局静态初始化一个互斥量mutex
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;  // 全局静态初始化一个条件变量cond

void *Count(void *args)
{
    pthread_detach(pthread_self());  // 线程分离
    uint64_t number = (uint64_t)args;
    std::cout << "pthread: " << number << " create success" << std::endl;

    while (true)
    {
        pthread_mutex_lock(&mutex);
        pthread_cond_wait(&cond, &mutex);

        std::cout << "pthread: " << number << ", cnt: " << cnt++ << std::endl;
        pthread_mutex_unlock(&mutex);
    }
}

int main()
{
    for (uint64_t i = 0; i < 5; ++i)
    {
        pthread_t tid;
        pthread_create(&tid, nullptr, Count, (void*)i);
        usleep(1); // 为了让子线程按顺序进入等待
    }
    
    sleep(3);
    std::cout << "main thread ctrl begin: " << std::endl;

    while (true)
    {
        sleep(1);
        pthread_cond_signal(&cond);  // 唤醒在条件变量cond等待队列中的第一个线程, 默认都是第一个线程
        // pthread_cond_broadcast(&cond);
        std::cout << "signal one thread..." << std::endl;
    }

    return 0;
}